﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using CoreEx.Database.Metadata;
using LinFu.IoC.Configuration;
using LinFu.IoC;
using LinFu.IoC.Interfaces;
using System.Linq;
namespace CoreEx.Database.MetaData.Implementation
{
    /// <summary>
    /// A repository of <see cref="ITypeMappingInfo"/> instances.
    /// </summary>
    public class TypeMappingRepository : ITypeMappingRepository, IInitialize
    {
        private readonly IDictionary<Type, ITypeMappingInfo> _repository 
            = new Dictionary<Type, ITypeMappingInfo>();
        
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeMappingRepository"/> class.
        /// </summary>
        /// <param name="repositoryName">The name of the repository.</param>
        public TypeMappingRepository(string repositoryName)
        {
            RepositoryName = repositoryName;
        }

        /// <summary>
        /// Gets the name of the repository.
        /// </summary>
        /// <value></value>
        public string RepositoryName { get; private set;}

        /// <summary>
        /// Gets the <see cref="ITypeMappingInfo"/> instance that corresponds to the <paramref name="type"/>
        /// </summary>
        /// <param name="type">The <see cref="Type"/> for which to return a <see cref="ITypeMappingInfo"/> instance.</param>
        /// <returns><see cref="ITypeMappingInfo"/></returns>
        public ITypeMappingInfo this[Type type]
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get
            {
                if (!_repository.ContainsKey(type))
                    _repository.Add(type,CreateTypeMapping(type));
                return _repository[type];
            }
        }

        private ITypeMappingInfo CreateTypeMapping(Type type)
        {
            var tableInfo = TableInfoMapper.MapFrom(type);
            ValidateTableInfo(type,tableInfo);
            var propertyMappingList = PropertyInfoMapper.MapFrom(type, tableInfo);
            var typeMappingInfo = new TypeMappingInfo
                                      {
                                          ColumnMappings = propertyMappingList,
                                          TableInfo = tableInfo,
                                          Type = type
                                      };
            return typeMappingInfo;
        }

        public ITableInfoMapper TableInfoMapper { get; set; }
        public IPropertyInfoMapper PropertyInfoMapper { get; set; }

        private void ValidateTableInfo(Type type, TableInfo tableInfo)
        {
            if (tableInfo.PrimaryKey == null)
                throw new MappingException(string.Format("Unable to map type '{0}'. The table '{1}' does not define a primary key",type.Name,tableInfo));
        }



        /// <summary>
        /// Initializes this <see cref="ITypeMappingRepository"/> instance
        /// </summary>
        /// <param name="source">The <see cref="IServiceContainer"/> that created this instance</param>
        public void Initialize(IServiceContainer source)
        {        
            TableInfoMapper = source.GetService<ITableInfoMapper>(null, new []{RepositoryName});
            PropertyInfoMapper = source.GetService<IPropertyInfoMapper>(null, new []{TableInfoMapper});   
        }
    }
}
